﻿using System.Web.Mvc;
using Dexter.CallContext;
using Dexter.Dependency;

namespace Dexter.Web.Mvc.Filters {
	/// <summary>
	/// This filter will manage the session for all of the controllers that needs a Raven Document Session.
	/// It does so by automatically injecting a session to the first public property of type IDocumentSession available
	/// on the controller.
	/// </summary>
	public class DexterCallFilter : ActionFilterAttribute {
		readonly IDexterCall dexterCall;
		readonly bool isReadOnly;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Web.Mvc.ActionFilterAttribute"/> class.
		/// </summary>
		public DexterCallFilter ( bool isReadOnly ) {
			this.isReadOnly = isReadOnly;
			this.dexterCall = DexterContainer.Resolve <IDexterCall> ( );
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Web.Mvc.ActionFilterAttribute"/> class.
		/// </summary>
		public DexterCallFilter ( IDexterCall dexterCall ) : this (dexterCall, false){
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Web.Mvc.ActionFilterAttribute"/> class.
		/// </summary>
		public DexterCallFilter ( IDexterCall dexterCall , bool isReadOnly ) {
			this.dexterCall = dexterCall;
			this.isReadOnly = isReadOnly;
		}

		public override void OnActionExecuting ( ActionExecutingContext filterContext ) {
			dexterCall.StartSession ( isReadOnly );
		}

		//NOTE: Is not good because fi the views load something with lazy load an exeception will be occured.
		public override void OnActionExecuted ( ActionExecutedContext filterContext ) {
			dexterCall.Complete ( filterContext.Exception == null );
		}
	}
}
